package com.hx.vending.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.hx.vending.annotation.Authorization;
import com.hx.vending.bean.*;
import com.hx.vending.bean.config.AlipayConfig;
import com.hx.vending.dao.*;
import com.hx.vending.mqtt.RunnerSendMqtt;
import com.hx.vending.service.ICustomerService;
import com.hx.vending.service.IMedicineService;
import com.hx.vending.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/12/21.
 */
@Service
public class CoustomerServiceImpl implements ICustomerService{
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private OnlineOrderMapper onlineOrderMapper;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private EquipmentMapper equipmentMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CustomerRechargeMapper customerRechargeMapper;
    @Resource
    private CapitalFlowMapper capitalFlowMapper;
    @Resource
    private UserWithdrawMapper userWithdrawMapper;
    @Resource
    private ICustomerService customerService;
    @Resource
    private MedicineMapper medicineMapper;

    private static Logger logger = Logger.getLogger(CoustomerServiceImpl.class);

    @Override
    public int saveOrUpdate(Customer record) {
        int i = customerMapper.countCustomerKey(record);
        if(i>0){
            return customerMapper.updateByPrimaryKeySelective(record);
        }else{
            return customerMapper.insertSelective(record);
        }
    }
    /*
    * 支付宝支付
    *  @param totalFee        标价金额：元
     * @param outTradeNoStr   商户订单号
     * @param onlineOrderId   线上订单id
     * @param equipmentId     设备id
     * @param goodsStr        购买的商品出货记录(货道,数量,货道,数量...)
    * */
    @Override
    public Object alipaypayment(Integer customerId,Integer onlineOrderId) {
        //查询客户信息
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        Customer selectCustomer = this.customerMapper.selectByPrimaryKeySelective(customer);
        if (ToolUtil.isEmpty(selectCustomer)) {
            return null;
        }
        //查询订单信息
        OnlineOrder onlineOrder = new OnlineOrder();
        onlineOrder.setOnlineOrderId(onlineOrderId);
        OnlineOrder selectOnlineOrder = this.onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);
        if (ToolUtil.isEmpty(selectOnlineOrder) || selectOnlineOrder.getOnlineOrderState() != 0) {
            return null;
        }
        //自定义数据(关于订单)
        String attch = selectOnlineOrder.getOnlineOrderId().toString() + "," + selectOnlineOrder.getOnlineOrderEquipmentId();
        String orderStr = "";
        String out_trade_no = selectOnlineOrder.getOnlineOrderMerchantNumber();
        String total_Money = selectOnlineOrder.getOnlineOrderMoney().toString();
        try {
            //Map<String, String> bizModel = new LinkedHashMap<String, String>(); // 公共实体
            Map<String, String> orderMap = new LinkedHashMap<String, String>(); // 订单实体
            //商户订单号
            orderMap.put("out_trade_no", out_trade_no);
            //商品标题
            orderMap.put("subject", "支付宝支付");
            //订单金额
            orderMap.put("total_amount", total_Money);
            //销售产品码
            orderMap.put("product_code", "FAST_INSTANT_TRADE_PAY");
            //orderMap.put("product_code", "QUICK_MSECURITY_PAY");
            //订单描述
            orderMap.put("body",attch);

            // 实例化客户端
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                    AlipayConfig.APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.input_charset,
                    AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
            AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest();
            // SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            // //描述信息 添加附加数据
            model.setBody(orderMap.get("body")); //商品信息
            model.setSubject(orderMap.get("subject")); // 商品名称
            model.setOutTradeNo(orderMap.get("out_trade_no")); // 商户订单号(自动生成)
            model.setTotalAmount(total_Money); // 支付金额
            model.setProductCode(orderMap.get("product_code")); // 销售产品码
            model.setTimeoutExpress("2h");
            //model.setTimeoutExpress("15m");
            model.setSellerId(AlipayConfig.PARTNER); // 商家id
            ali_request.setBizModel(model);
            ali_request.setNotifyUrl(AlipayConfig.notify_url); // 回调地址
            //ali_request.setReturnUrl(AlipayConfig.return_url);
            AlipayTradeAppPayResponse responses = client.sdkExecute(ali_request);
            orderStr = responses.getBody();
            System.err.println("返回的：tradeNo========="+ responses.getBody()); // 就是orderString 可以直接给客户端请求，无需再做处理
        }catch(AlipayApiException e){
            e.printStackTrace();
            logger.info("与支付宝交互出错，未能生成订单，请检查代码！");
        }
        return orderStr;
    }

    @Override
    public String notify(HttpServletRequest request){
        System.out.println("进入支付宝回调函数=====================");
        Map<String,String> params = new HashMap<>();
        // 1.从支付宝回调的request域中取值
        Map<String, String[]> requestParams = request.getParameterMap();
        //System.out.println("从支付宝回调的request域中取值:requestParams============================");
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //System.out.println("app_id====================="+params.get("app_id"));
        //System.out.println("trade_no====================="+params.get("trade_no"));
        // 2.封装必须参数
        String out_trade_no = request.getParameter("out_trade_no"); // 商户订单号
        //System.err.println("out_trade_no==================================" + out_trade_no);
        String orderType = request.getParameter("body"); // 订单内容
        //System.out.println("orderType==================================" + orderType);
        String tradeStatus = request.getParameter("trade_status"); // 交易状态
        //System.err.println("tradeStatus=================================" + tradeStatus);
        // 3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;
        try {
            // 3.1调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.input_charset,AlipayConfig.sign_type);
            //System.out.println("========="+signVerified);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 4.对验签进行处理
        if (signVerified){ // 验签通过
            if (tradeStatus.equals("TRADE_SUCCESS")) {// 只处理支付成功的订单:修改交易表状态,支付成功
                //当单内容orderType
                String [] attach = orderType.split(",");//(线上订单号+设备id)
                //线上订单id
                Integer onlineOrderId = Integer.parseInt(attach[0]);
                //设备id
                String equipmentId = attach[1];


                //4位随机数
                //String fourNumber = ToolUtil.generateNonceStr();
                //判断订单
                OnlineOrder onlineOrder = new OnlineOrder();
                //System.out.println("创建对象=============");
                onlineOrder.setOnlineOrderId(onlineOrderId);
                //System.out.println("订单id============="+onlineOrderId);
                OnlineOrder selectOnlineOrder = this.onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);
                if (ToolUtil.isNotEmpty(selectOnlineOrder)) {
                    if (selectOnlineOrder.getOnlineOrderState() == 1 || selectOnlineOrder.getOnlineOrderState() == 2) {
                        //System.out.println("======================file");
                        //已经支付过的订单
                        return "fail";
                    }else {
                        //System.out.println("交易订单号================"+params.get("trade_no"));
                        //已支付状态
                        //System.out.println("用户userId========"+request.getParameter("buyer_id"));
                        onlineOrder.setOnlineOrderOpenid(request.getParameter("buyer_id"));
                        onlineOrder.setOnlineOrderState(1);
                        onlineOrder.setOnlineOrderType("2");
                        onlineOrder.setOnlineOrderEquipmentId(equipmentId);
                        //交易订单号
                        onlineOrder.setOnlineOrderDealNumber(params.get("trade_no"));
                        this.onlineOrderMapper.updateByPrimaryKeySelective(onlineOrder);
                    }
                }

                String totalMoney = params.get("total_amount");
                //System.out.println("==================》》》交易金额"+ totalMoney);
                //订单推送
                Equipment equipment = new Equipment();
                equipment.setEquipmentId(equipmentId);
                Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);
                User user = new User();
                user.setUserId(selectEquipment.getEquipmentUserId());
                User selectUser = this.userMapper.selectByPrimaryKey(user);
                User u1 = new User();
                u1.setUserId(selectUser.getUserId());
                if(selectUser.getUserMoney() == 0 || ToolUtil.isEmpty(selectUser.getUserMoney())){
                    u1.setUserMoney(Double.parseDouble(totalMoney));
                    u1.setUserAlipayBalance(Double.parseDouble(totalMoney));
                }
                u1.setUserAlipayBalance(BigDecimalUtils.add(selectUser.getUserAlipayBalance(),Double.parseDouble(totalMoney)));
                u1.setUserMoney(BigDecimalUtils.add(selectUser.getUserMoney(),Double.parseDouble(totalMoney)));
                userMapper.updateByPrimaryKeySelective(u1);
                System.out.println("=================修改余额成功");
                //添加流水
                CapitalFlow capitalFlow = new CapitalFlow();
                capitalFlow.setCapitalFlowUserId(selectUser.getUserId());
                capitalFlow.setCapitalFlowTransactionNumber(params.get("trade_no"));
                capitalFlow.setCapitalFlowTransactionAmount(Double.parseDouble(totalMoney));
                //支付宝
                capitalFlow.setCapitalFlowPaymentType(2);
                //商户收益
                capitalFlow.setCapitalFlowTransactionType(3);
                capitalFlow.setCapitalFlowTime(DateUtil.getTime());
                capitalFlow.setCapitalFlowUserMoney(BigDecimalUtils.add(selectUser.getUserMoney(),Double.parseDouble(totalMoney)));
                //已完成
                capitalFlow.setCapitalFlowState(2);
                capitalFlow.setCapitalFlowRemarks("商户收益");
                capitalFlowMapper.insertSelective(capitalFlow);

                Medicine m = new Medicine();
                m.setMedicineOrderId(onlineOrderId);
                m.setMedicineStatus(1);
                medicineMapper.updateByPrimaryKeySelective(m);

                OnlineOrder o = onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);

                //System.out.println("订单推送================="+selectUser.getUserOrderPush());
                //System.out.println("商家id================="+selectUser.getUserAccount());
                try {
                    if (selectUser != null && selectUser.getUserOrderPush().equals("1")) {
                        String pushMessage = "订单推送详情:\n设备ID:%s\n商家订单号:%s\n支付宝交易号:%s\n订单金额:%s\n支付方式:%s";
                        String orderType1 = null;
                        if (o.getOnlineOrderType().equals("1")) {
                            orderType1 = "微信";
                        } else if (o.getOnlineOrderType().equals("2")) {
                            orderType1 = "支付宝";
                        }

                        PushUtils.getInstance().pushMessage(selectUser.getUserAccount(), String.format(pushMessage, selectEquipment.getEquipmentId(), o.getOnlineOrderMerchantNumber(),
                                o.getOnlineOrderDealNumber(), o.getOnlineOrderMoney(),orderType1));
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
                //发送MQTT消息
                RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
                runnerSendMqtt.setMessage(equipmentId);
                //System.out.println("设备id============="+equipmentId);
                runnerSendMqtt.setRedisTemplate(redisTemplate);
                runnerSendMqtt.setTheme("Delivery");
                runnerSendMqtt.setThreadName("出货指令");
                runnerSendMqtt.setRedisKey("DeliveryReceive-" + equipmentId);
                runnerSendMqtt.setOnlineOrderId(onlineOrderId);
                //System.out.println("==================>>>>发送指令");
                runnerSendMqtt.start();
                return "success";
            }else if(tradeStatus.equals("TRADE_CLOSED")){
                //当单内容orderType
                String [] attach = orderType.split(",");//(线上订单号+设备id)
                //线上订单id
                Integer onlineOrderId = Integer.parseInt(attach[0]);
                OnlineOrder onlineOrder = new OnlineOrder();
                //System.out.println("创建对象=============");
                onlineOrder.setOnlineOrderId(onlineOrderId);
                OnlineOrder selectOnlineOrder = this.onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);
                if (ToolUtil.isNotEmpty(selectOnlineOrder)) {
                    if (selectOnlineOrder.getOnlineOrderState().equals(1) || selectOnlineOrder.getOnlineOrderState().equals(2)) {
                        //已经支付过的订单
                    }else {
                        //System.out.println("用户userId========"+request.getParameter("buyer_id"));
                        onlineOrder.setOnlineOrderOpenid(request.getParameter("buyer_id"));
                        onlineOrder.setOnlineOrderState(2);
                        onlineOrder.setOnlineOrderType("2");
                        onlineOrder.setOnlineOrderEquipmentId(attach[1]);
                        //交易订单号
                        onlineOrder.setOnlineOrderDealNumber(params.get("trade_no"));
                        int i = onlineOrderMapper.updateByPrimaryKeySelective(onlineOrder);
                        if(i > 0){
                            return "fail";
                        }
                    }
                }
                return "fail";
            }
        }else{
            return "fail";
        }
        return "fail";
    }

    @Override
    public String notifyRefund(HttpServletRequest request) {
        System.out.println("进入支付宝退款回调函数=====================");
        /*Map<String,String> params = new HashMap<>();
        // 1.从支付宝回调的request域中取值
        Map<String, String[]> requestParams = request.getParameterMap();
        System.out.println("从支付宝回调的request域中取值:requestParams============================");
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);

        }*/
        if(Integer.parseInt(request.getParameter("success_num")) > 0){

        }
        return null;
    }

    @Override
    public ModelAndView  returnUrl(HttpServletRequest request) {
        System.out.println("============进入同步回调returnUrl");
        Map<String,String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);

        }
        String tradeStatus = request.getParameter("trade_status"); // 交易状态
        // 3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;
        try {
            // 3.1调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.input_charset,AlipayConfig.sign_type);
            System.out.println("========="+signVerified);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(signVerified){
            System.out.println("===================验证通过");
               if(tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")){
                   OnlineOrder o = new OnlineOrder();
                   o.setOnlineOrderMerchantNumber(params.get("out_trade_no"));
                   OnlineOrder onlineOrder = onlineOrderMapper.selectByPrimaryKeySelective(o);
                   ModelAndView mv = new ModelAndView("redirect:"+ Constant.REDIRECTURL+"/"+onlineOrder.getOnlineOrderId());
                   return mv;
               }
        }
        return null;
    }


    /**
     * 根据id查询客户信息
     * @param customerId
     * @return
     */
    public Msg selectCustomerById(Integer customerId) {

        if (ToolUtil.isNotEmpty(customerId)) {

            Customer customer = new Customer();
            customer.setCustomerId(customerId);
            Customer selectCustomer = this.customerMapper.selectByPrimaryKeySelective(customer);

            if (ToolUtil.isNotEmpty(selectCustomer)) {
                return Msg.success().add("customer", selectCustomer);
            }else {
                return Msg.fail();
            }
        }else {
            return Msg.fail();
        }
    }

    @Override
    public Customer selectByPrimary(Customer customer) {
        return customerMapper.selectByPrimaryKeySelective(customer);
    }

    @Override
    public int insertCustomerRecharge(CustomerRecharge customerRecharge) {
        return customerRechargeMapper.insertSelective(customerRecharge);
    }

    @Override
    public CustomerRecharge selectRechargeByPrimary(CustomerRecharge customerRecharge) {
        return customerRechargeMapper.selectByPrimaryKeySelective(customerRecharge);
    }

    @Override
    public Msg withdraw(Double amount,Integer userId,Integer type) {

        User u = new User();
        u.setUserId(userId);
        User user = userMapper.selectByPrimaryKey(u);
        if(user.getUserMoney() < amount){
            return Msg.fail().add("msg","提现金额超过余额");
        }
        if(user.getUserAlipayBalance() < amount){
            return Msg.fail().add("msg","支付宝余额不足");
        }
        Float float1 = user.getUserWithdrawproportion();//// 商户提现比例
        double double1 = Double.parseDouble(float1.toString());
        double pool = BigDecimalUtils.mul(amount, double1 / 100);// 手续费

        pool = BigDecimalUtils.round(Math.ceil(pool*100), 100, 2);//手续费

        //实际到账金额
        Double subMoney = BigDecimalUtils.sub(amount, pool);// 提现减去提现手续费

        String out_biz_no = DateUtil.getAllTime()+ToolUtil.generateNonceStr(4);
        // 实例化客户端
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                AlipayConfig.APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.input_charset,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);
        AlipayFundTransToaccountTransferRequest transferAccounts_request = new AlipayFundTransToaccountTransferRequest();
        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
        model.setOutBizNo(out_biz_no);
        model.setPayeeType("ALIPAY_LOGONID");
        model.setPayeeAccount(user.getUserAlipayNumber());
        //提现金额
        model.setAmount(subMoney.toString());
        //model.setPayerShowName(payer_show_name);
        model.setPayeeRealName(user.getUserAlipayRealName());
        model.setRemark("提现");
        transferAccounts_request.setBizModel(model);
        try {
            AlipayFundTransToaccountTransferResponse response = client.execute(transferAccounts_request);
            if(response.isSuccess()){
                System.out.println("===========商户单号"+response.getOutBizNo());
                System.out.println("===========转账单据号"+response.getOrderId());
                System.out.println("===========时间"+response.getPayDate());
                //添加流水
                CapitalFlow capitalFlow = new CapitalFlow();
                capitalFlow.setCapitalFlowUserId(userId);
                capitalFlow.setCapitalFlowTransactionNumber(response.getOrderId());
                capitalFlow.setCapitalFlowTransactionAmount(amount);
                capitalFlow.setCapitalFlowPaymentType(2);
                capitalFlow.setCapitalFlowTransactionType(1);
                capitalFlow.setCapitalFlowTime(response.getPayDate());
                capitalFlow.setCapitalFlowUserMoney(BigDecimalUtils.sub(user.getUserMoney(),amount));
                capitalFlow.setCapitalFlowState(2);
                capitalFlow.setCapitalFlowRemarks("支付宝提现到零钱");
                capitalFlowMapper.insertSelective(capitalFlow);
                CapitalFlow c = capitalFlowMapper.selectByPrimaryKeySelective(capitalFlow);
                UserWithdraw userWithdraw = new UserWithdraw();
                userWithdraw.setUserWithdrawUserid(userId);
                userWithdraw.setUserWithdrawMoney(amount);
                userWithdraw.setUserWithdrawPractical(subMoney);
                //商户单号
                userWithdraw.setUserWithdrawOutBizNo(response.getOutBizNo());
                //支付宝转账单据号
                userWithdraw.setUserWithdrawOrderNo(response.getOrderId());
                userWithdraw.setUserWithdrawTime(response.getPayDate());
                userWithdraw.setUserWithdrawAccount(DateUtil.getTime());
                userWithdraw.setUserWithdrawState(2);
                userWithdraw.setUserWithdrawType(type);
                userWithdraw.setUserWithdrawRemark("提现成功");
                userWithdraw.setUserWithdrawFlowId(c.getCapitalFlowId());
                userWithdraw.setUserWithdrawBankNumber(user.getUserAlipayNumber());
                userWithdrawMapper.insertSelective(userWithdraw);
                //修改余额
                Double countMoney = BigDecimalUtils.sub(user.getUserMoney(),amount);
                //System.out.println("账户余额==============="+countMoney);
                u.setUserMoney(countMoney);
                Double alipayMoney = BigDecimalUtils.sub(user.getUserAlipayBalance(),amount);
                // System.out.println("支付宝余额==============="+alipayMoney);
                u.setUserAlipayBalance(alipayMoney);
                userMapper.updateByPrimaryKeySelective(u);
                System.out.println(response.getBody());
                return Msg.success().add("msg","提现成功");
            } else {
                /*//添加流水
                CapitalFlow capitalFlow = new CapitalFlow();
                capitalFlow.setCapitalFlowUserId(userId);
                capitalFlow.setCapitalFlowTransactionNumber(response.getOrderId());
                capitalFlow.setCapitalFlowTransactionAmount(amount);
                capitalFlow.setCapitalFlowPaymentType(2);
                capitalFlow.setCapitalFlowTransactionType(1);
                capitalFlow.setCapitalFlowTime(DateUtil.getTime());
                capitalFlow.setCapitalFlowUserMoney(user.getUserMoney());
                capitalFlow.setCapitalFlowState(3);
                capitalFlow.setCapitalFlowRemarks("商户提现失败");
                capitalFlowMapper.insertSelective(capitalFlow);
                CapitalFlow c = capitalFlowMapper.selectByPrimaryKeySelective(capitalFlow);*/
                UserWithdraw userWithdraw = new UserWithdraw();
                userWithdraw.setUserWithdrawMoney(amount);
                //商户单号
                userWithdraw.setUserWithdrawOutBizNo(response.getOutBizNo());
                //支付宝转账单据号
                userWithdraw.setUserWithdrawOrderNo(response.getOrderId());
                userWithdraw.setUserWithdrawTime(response.getPayDate());
                userWithdraw.setUserWithdrawAccount(DateUtil.getTime());
                userWithdraw.setUserWithdrawType(1);
                userWithdraw.setUserWithdrawState(0);
                userWithdraw.setUserWithdrawUserid(userId);
                userWithdraw.setUserWithdrawRemark("提现失败");
                //userWithdraw.setUserWithdrawFlowId(c.getCapitalFlowId());
                userWithdraw.setUserWithdrawBankNumber(user.getUserAlipayNumber());
                userWithdrawMapper.insertSelective(userWithdraw);
                System.out.println("调用失败");
                System.out.println("提现失败错误码============"+response.getSubCode());
                if(response.getSubCode().equals("PAYER_BALANCE_NOT_ENOUGH")){
                    try {
                        String pushMessage = "账户异常:\n异常类型:支付宝账户提现余额不足";
                        PushUtils.getInstance().pushMessage("18654568090",String.format(pushMessage));
                        PushUtils.getInstance().pushMessage("15562649697",String.format(pushMessage));
                        return Msg.fail().add("msg","服务器正在忙于结算，请5-10分钟后再试!");
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
                return Msg.fail().add("msg",response.getSubMsg());
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
        }
        return Msg.fail();
    }

    @Override
    public String aliPayExchangeRedirectWeb(String auth_code, String state) {
        System.out.println("支付宝授权登陆回调");
        System.out.println("auth_code："+auth_code);
        System.out.println("EquipmentId====="+state);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        //实例化支付宝API对象
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.APPID, AlipayConfig.APP_PRIVATE_KEY, "json", "UTF-8", AlipayConfig.ALIPAY_PUBLIC_KEY, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        //交易令牌值
        request.setCode(auth_code);
        //固定值
        request.setGrantType("authorization_code");
        //token值
        String auth_token = "";

        AlipaySystemOauthTokenResponse oauthTokenResponse = null;
        String id = "";
        try{

            oauthTokenResponse = alipayClient.execute(request);
            System.out.println("access_token："+ oauthTokenResponse.getAccessToken());
            if (null != oauthTokenResponse.getAccessToken() && null != oauthTokenResponse.getRefreshToken()) {
                //获取token值
                auth_token = oauthTokenResponse.getAccessToken();
                //第四步：调用接口获取用户信息
                AlipayUserInfoShareRequest shareRequest = new AlipayUserInfoShareRequest();
                AlipayUserInfoShareResponse userinfoShareResponse = null;
                try {
                    userinfoShareResponse = alipayClient.execute(shareRequest, auth_token);
                } catch (AlipayApiException e) {
                    //处理异常
                    e.printStackTrace();
                }

                Customer customer = new Customer();

                //支付宝唯一id
                customer.setCustomerOpenId(userinfoShareResponse.getUserId());
                //昵称
                customer.setCustomerName(userinfoShareResponse.getNickName());
                //支付宝用户头像
                customer.setCustomerPhoto(userinfoShareResponse.getAvatar());
                //省份
                customer.setCustomerProvince(userinfoShareResponse.getProvince());
                //城市
                customer.setCustomerCity(userinfoShareResponse.getCity());
                customer.setCustomerType(2);
                //性别
                if (userinfoShareResponse.getGender().equals("M")) {
                    //M为男性
                    customer.setCustomerSex("1");
                } else if (userinfoShareResponse.getGender().equals("F")) {
                    //F未女性
                    customer.setCustomerSex("2");
                } else {
                    //0为未知
                    customer.setCustomerSex("0");
                }
                //查询设备信息
                Equipment equipment = new Equipment();
                equipment.setEquipmentId(state);
                Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);
                if (ToolUtil.isEmpty(selectEquipment) || ToolUtil.isEmpty(selectEquipment.getEquipmentUserId())) {
                    return "该设备下无商户注册！";
                }
                //存在则更新，不存在则保存
                customerService.saveOrUpdate(customer);
                Customer c = new Customer();
                c.setCustomerOpenId(userinfoShareResponse.getUserId());
                Customer cc = customerMapper.selectByPrimaryKeySelective(c);

                if(ToolUtil.isNotEmpty(cc)){
                    CustomerRecharge cr1 = new CustomerRecharge();
                    cr1.setCustomerRechargeUserId(selectEquipment.getEquipmentUserId());
                    cr1.setCustomerRechargeCustomerId(cc.getCustomerId());
                    CustomerRecharge cr = customerRechargeMapper.selectByPrimaryKeySelective(cr1);
                    if(ToolUtil.isEmpty(cr)){
                        CustomerRecharge customerRecharge = new CustomerRecharge();
                        customerRecharge.setCustomerRechargeUserId(selectEquipment.getEquipmentUserId());
                        customerRecharge.setCustomerRechargeCustomerId(cc.getCustomerId());
                        customerRechargeMapper.insertSelective(customerRecharge);
                        id= cc.getCustomerId().toString();
                        //实例化一个Cookie
                        Cookie cookie = new Cookie("customerId",cc.getCustomerId().toString());
                        //生存时间
                        cookie.setMaxAge(3600 * 24);
                        //设置cookie路径
                        cookie.setPath("/");
                        //写入肯定是要用response
                        response.addCookie(cookie);
                    }else{
                        System.out.println("买家id================="+cr.getCustomerRechargeCustomerId());
                        id = cr.getCustomerRechargeCustomerId().toString();
                        //实例化一个Cookie
                        Cookie cookie = new Cookie("customerId",cr.getCustomerRechargeCustomerId().toString());
                        //生存时间
                        cookie.setMaxAge(3600 * 24);
                        //设置cookie路径
                        cookie.setPath("/");
                        //写入肯定是要用response
                        response.addCookie(cookie);
                    }
                }


            }else {
                System.out.println("---------------------交换令牌和刷新令牌获取为空,直接返回页面-----------------");
            }
        }catch(AlipayApiException e){
            System.out.println("捕捉到异常信息为:" + e.getMessage());
            System.out.println("错误码:" + e.getErrCode() + ",错误信息:" + e.getErrMsg());
            e.printStackTrace();

        }
        return "redirect:"+Constant.REDIRECTWEBURL + "/" +state+"/"+id;
    }


}
